package application;

import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL15.*;
import static org.lwjgl.opengl.GL20.*;

import java.util.Arrays;


import org.lwjgl.input.*;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.GL11;

import data.ResourcesManager;

import parameters.Color3b;
import parameters.Vec2f;

import event.KeyboardEvent;
import event.MouseEvent;
import game.Game;

public class Application implements Runnable {
	private Thread thread;
	private Window window;
	
	private ResourcesManager resourcesManager;
	private Game game;
	private ServerHandler serverHandler;
	
	private boolean running = false;
	
	/**
	 * Creates application
	 * new thread for it :P
	 */
	
	public Application(){
		thread = new Thread(this, "Application Thread");
		System.out.println("[i] Created " + thread.getName());
		
		thread.start();
	}
	
	/**
	 * Start application
	 */
	
	@Override
	public void run() {
		running = true;
		
		//Creating Window
		window = new Window();
		
		//Loading resources + creating game
		resourcesManager	= new ResourcesManager();
		game				= new Game(resourcesManager);
		serverHandler		= new ServerHandler(game);
		
		window.disableTextureSmoothing();
		window.enableTexturing();
		
		//GAME LOOP
		while(running){
			window.clear();

			handleKeyboardEvents();
			handleMouseEvents();
				
			game.update(System.currentTimeMillis() - window.popTime());
			
			window.pushTime();
			
			game.redraw();
			
			window.update();
		}	
		serverHandler.stop();
	}
	
	/**
	 * Stops application
	 */
	
	public void stop() {
		running = false;
	}
	
	/**
	 * Events handling...
	 */
	
	public void handleKeyboardEvents(){
		if(Keyboard.next()){
			KeyboardEvent event = new KeyboardEvent(Keyboard.getEventKey(), Keyboard.getEventKeyState());
			
			if(event.key == Keyboard.KEY_ESCAPE){
				serverHandler.stop();
				stop();
			}
			
			game.handleKeyboardEvent(event);
		}
	}
	
	public void handleMouseEvents(){
		if(Display.isCloseRequested()) stop();
		
		if(Mouse.next()){
			MouseEvent event = new MouseEvent(new Vec2f(Mouse.getEventX(), Mouse.getEventX()), Mouse.getEventButton(), Mouse.getEventButtonState());
			
			game.handleMouseEvent(event);
		}
	}
}
